package server

import (
	"bufio"
	"log"
	"net"
)

// TcpConnection 服务器端接收的TCP连接, 连接设备
type TcpConnection struct {
	session *Session
	conn    *net.TCPConn
	puId    string
	connId  uint8
}

func NewTcpConnection(session *Session, conn *net.TCPConn, puId string, connId uint8) *TcpConnection {
	return &TcpConnection{
		session: session,
		conn:    conn,
		puId:    puId,
		connId:  connId,
	}
}

func (tis *TcpConnection) Open() {

	log.Printf("通知设备connect")
	tis.session.Write(&JsonProto{
		Method: ProtoMethodConnect,
		ConnId: tis.connId,
	})
}

func (tis *TcpConnection) Close() {
	tis.session.Write(&JsonProto{
		Method: ProtoMethodClose,
		ConnId: tis.connId,
	})
}

func (tis *TcpConnection) Write(object *JsonProto) {
	// 加锁
	_, _ = tis.conn.Write(object.Data)
}

func (tis *TcpConnection) CloseConnection() {
	log.Println("关闭连接")
	_ = tis.conn.Close()
}

func (tis *TcpConnection) readLoop(r *bufio.Reader) {

	buffer := make([]byte, 1024)
	for {
		n, err := r.Read(buffer)
		if n > 0 {
			data := buffer[:n]
			_ = data

			tis.session.Write(&JsonProto{
				Method: ProtoMethodMsg,
				ConnId: tis.connId,
				Data:   data,
			})
		}

		if err != nil {
			break
		}
	}
}
